#include "../LOG_true/toplog.h"
#include <chrono>

void bench(const string &logger_name, size_t thread_count, size_t msg_count, size_t msg_len)
{
    // 1.获取日志器
    TopLog::Logger::ptr logger = TopLog::Getsingleton(logger_name);
    if (logger.get() == nullptr)
    {
        return;
    }

    std::cout << "测试日志" << msg_count << "条,总大小:" << (msg_count * msg_len) / 1024 << "KB" << std::endl;
    // 2.组织指定日志消息长度
    std::string msg(msg_len - 1, 'c');
    // 3.创建线程数量
    vector<std::thread> _threads;
    vector<double> cost_array(thread_count);
    size_t msg_per_thr = msg_count / thread_count; // 日志总量/线程数量  平局每个线程输出的数量
    for (int i = 0; i < thread_count; i++)
    {
        // 创建并构造
        _threads.emplace_back([&, i]()
                              {
            // 函数计时
            auto start = std::chrono::high_resolution_clock::now();
            // 开始循环写日志
            for (int j = 0; j < msg_per_thr; j++)
            {
                logger->fatal("%s", msg.c_str());
            }

            // 线程函数内部结束计时
            auto end = std::chrono::high_resolution_clock::now();
            std::chrono::duration<double> cost = end - start; // 时间消耗时间
            cost_array[i] = cost.count();
            std::cout << "\t线程:" << i << ":" << "\t输出数量:" << msg_per_thr << ", 耗时:" << cost.count()
            << "s" << std::endl; });
    }

    for (int i = 0; i < thread_count; i++)
    {
        _threads[i].join();
    }

    // 计算并行线程 计算出总时间（最大时间）秒数
    double max_cost = cost_array[0];
    for (size_t i = 0; i < thread_count; i++)
    {
        max_cost = max(max_cost, cost_array[i]);
    }
    size_t msg_per_sec = msg_count / max_cost; // 每秒输出总量
    size_t size_per_sec = (msg_count * msg_len) / (max_cost * 1024);

    // 进行输出打印
    std::cout << "\t总耗时:" << max_cost << "s" << std::endl;
    std::cout << "\t每秒输出日志数量:" << msg_per_sec << "条" << std::endl;
    std::cout << "\t每秒输出日志大小:" << size_per_sec << "KB" << std::endl;
}

void syncbench()
{
    std::unique_ptr<TopLog::LoggerBuilder> builder(new TopLog::GloBalLoggerBuilder()); // 智能指针管理对象
    builder->buildLoggerType(TopLog::LoggerType::LOGGER_SYNC);
    builder->buildLoggerName("snyc_logger");
    builder->buildLoggerFamtter("%m%n");
    builder->buildSink<TopLog::StdoutSink>();
    builder->buildSink<TopLog::FileSink>("./logs/sync.log");
    builder->build();
    bench("snyc_logger", 4, 10000, 100);
}
void asyncbench()
{
    std::unique_ptr<TopLog::LoggerBuilder> builder(new TopLog::GloBalLoggerBuilder()); // 智能指针管理对象
    builder->buildLoggerType(TopLog::LoggerType::LOGGER_ASYNC);
    builder->buildLoggerName("asnyc_logger");
    builder->buildLoggerFamtter("%m%n");
    builder->buildSink<TopLog::RollSink>("./logs/async.log",10*1024*1024);
    builder->build();
    bench("asnyc_logger", 3, 100000, 100);
}

int main()
{

    asyncbench();
    return 0;
}